package com.llkj.safeearth.httpUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;

/**
 * 异步数据请求
 */
public class AnsynHttpRequest {

    public static final int POST = 1; // post 提交
    public static final int GET = 2; // get 提交

    public static final int SUCCESS_HTTP = 0;
    public static final int FAILURE_HTTP = 1;
    public static final int FAILURE_NETWORK = 2;

    /***
     * get和post请求方法
     *
     * @param sendType 请求类型：get和post
     * @param url      请求地址
     * @param map      post使用到的
     * @param callBack 异步回调
     * @param i        请求的方法对应的int值（整个项目中唯一不重复的）
     */
    public static void requestGetOrPost(final Context c, final int sendType, String url,
                                        final Map<String, String> map, final ObserverCallBack callBack, final int i) {
        if (!isNetworkConnected(c) && callBack != null) {
            callBack.handleResult(null, FAILURE_NETWORK, i);
            return;
        }

        switch (sendType) {
            case POST:
                if (map != null) {
                    Log.e("Log","接口post==" + url + map.toString());
                }
                OkHttpUtils
                        .post().url(url).params(map).tag(c).build().connTimeOut(20 * 1000)
                        .execute(new StringCallback() {

                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (callBack != null) {
                                    callBack.handleResult(e.toString(), FAILURE_HTTP,
                                            i);
                                }
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (callBack != null) {
                                    callBack.handleResult(response, SUCCESS_HTTP,
                                            i);
                                }
                            }

                        });
                break;
            case GET:
                final StringBuffer sb = new StringBuffer();
                sb.append(url);
                if (map != null) {
                    if (!url.endsWith("?")) {
                        sb.append("&");
//                        sb.append("?");
                    }
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        String value = map.get(key);
                        if (value == null) {
                            continue;
                        }
                        value = value.replace(" ", "");
                        sb.append(key).append("=").append(value).append("&");
                    }
                    if (sb.toString().endsWith("&")) {
                        sb.deleteCharAt(sb.toString().length() - 1);
                    }
                }
                if (map != null) {
                    Log.e("Log","接口get==" + sb.toString());
                }
                OkHttpUtils
                        .get().url(url).params(map).tag(c).build().connTimeOut(20 * 1000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (callBack != null) {
                                    callBack.handleResult(e.toString(), FAILURE_HTTP,
                                            i);
                                }
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (callBack != null) {
                                    callBack.handleResult(response, SUCCESS_HTTP,
                                            i);
                                }
                                Log.e("Log",response);
                            }

                        });
                break;
            default:
                break;
        }
    }

    /***
     * post请求方法，直接上传数据
     *
     * @param url      请求地址
     * @param callBack 异步回调
     * @param i        请求的方法对应的int值（整个项目中唯一不重复的）
     */
    public static void requestPostString(Context c, String url, String content, final ObserverCallBack callBack, final int i) {
        if (!isNetworkConnected(c)) {
            callBack.handleResult(null, FAILURE_NETWORK, i);
            return;
        }
        Log.e("Log", url + "=====" + content);
        OkHttpUtils.postString().url(url).content(content).tag(c).build().connTimeOut(20 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        callBack.handleResult(e.toString(), FAILURE_HTTP,
                                i);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        callBack.handleResult(response, SUCCESS_HTTP,
                                i);
                        Log.e("Log", response);
                    }

                });
    }

    public interface ObserverCallBack {
        /**
         * @param data     返回的数据 json
         * @param encoding
         * @param method   判断是哪个接口返回的数据
         */

        void handleResult(String data, int encoding, int method);
    }
    /**
     * 判断当前是否有网络
     *
     * @author lvliuyan
     * @param context
     * @return
     */
    private static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
}
